package com.cn.zsc.config;

import com.mysql.cj.jdbc.MysqlDataSource;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@MapperScan(value = "com.cn.zsc.dblocal.dao", sqlSessionFactoryRef="sqlSessionFactoryBeanLocal")
public class ConfigDbLocal {

//    @Bean("dbLocal")
//    public DataSource dbLocal(){
//        MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
//        mysqlXADataSource.setUser("root");
//        mysqlXADataSource.setPassword("123456");
//        mysqlXADataSource.setUrl("jdbc:mysql://localhost:3306/xa-local?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false");
//        // 需要用AtomikosDataSource数据源管理
//        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
//        atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
//        return atomikosDataSourceBean;
//    }

    @Bean("dbLocal")
    public DataSource dbLocal(){
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        mysqlDataSource.setUrl("jdbc:mysql://localhost:3306/xa-local?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false");
        return mysqlDataSource;
    }

    @Bean("sqlSessionFactoryBeanLocal")
    public SqlSessionFactoryBean sqlSessionFactoryBean(@Qualifier("dbLocal") DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("mybatis/dbLocal/*.xml"));

        return sqlSessionFactoryBean;
    }


}
